//
//  LeiDaViewController.m
//  StationManager
//
//  Created by 泽华伟业 on 17/3/14.
//  Copyright © 2017年 Helong. All rights reserved.
//

#import "LeiDaViewController.h"
#import "DataHandel.h"
#import "TimeLabel.h"

@interface LeiDaViewController ()<UIScrollViewDelegate>

@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic,strong) NSMutableArray *imageArray;

@property (nonatomic,strong) NSMutableArray *timeArray;

@property (nonatomic,strong) UIScrollView *imgScrollView;

@property (nonatomic,strong) UIImageView *imageView;
//开始暂停按钮
@property (nonatomic,strong) UIButton *actionOrStopBtn;
//上一页按钮
@property (nonatomic,strong) UIButton *backBtn;
//下一页按钮
@property (nonatomic,strong) UIButton *nextBtn;

@end

@implementation LeiDaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"雷达实况";
    self.view.backgroundColor = [UIColor whiteColor];
    _imageArray = [NSMutableArray array];
    _timeArray = [NSMutableArray array];
    [self addImgScrollView];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[DataHandel sharedDataHandel]getLeiDaSumDataWithBlock:^(id object) {
        NSArray * leidaArray = (NSArray *)object;
        if (leidaArray.count == 0) {

            return ;
        }
        for (NSDictionary *dict in leidaArray) {
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dict objectForKey:@"path"]]]];
            ///将图片和时间分别加进数组
            [_timeArray addObject:[self getTimeStringWithString:[dict objectForKey:@"time"]]];
            if (image != nil) {
                 [_imageArray addObject:image];
            }else{
                //请求失败
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = @"请求失败";
                hud.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5f];
                hud.offset = CGPointMake(0.f, 200);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
                });

            }
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self addTimeLabelWithArray:_timeArray];
        [_imageView setImage:[_imageArray objectAtIndex:_imageArray.count -1]];
    }];
    [self addSomebutton];
}

//处理字符串得到时间字符串
- (NSString *)getTimeStringWithString:(NSString *)string{
    NSString *hourStr = @"";
    //处理小时数据
    int num = (int)([[string substringWithRange:NSMakeRange(8, 2)] integerValue] + 8);
    if (num >= 24) {
        num = num -24;
    }
    if (num < 10){
        hourStr = [NSString stringWithFormat:@"0%d",num];
    }else{
        hourStr = [NSString stringWithFormat:@"%d",num];
    }
    NSString *minString = [string substringWithRange:NSMakeRange(10, 2)];
    return [NSString stringWithFormat:@"%@:%@",hourStr,minString];
}
//添加ScrollView和imageView
- (void)addImgScrollView{
    _imgScrollView = [[UIScrollView alloc]init];
    [self.view addSubview:_imgScrollView];
    _imgScrollView.delegate = self;
    [_imgScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.equalTo(self.view).multipliedBy(0.75);
    }];

    _imageView = [[UIImageView alloc]init];
    [_imgScrollView addSubview:_imageView];
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(_imgScrollView);
    }];

    _imgScrollView.bounces = NO;
    _imgScrollView.contentSize = _imageView.image.size;
    _imgScrollView.maximumZoomScale = 1.5;
    _imgScrollView.minimumZoomScale = 0.8;
}

#pragma mark -- 添加时间lebel
- (void)addTimeLabelWithArray:(NSArray *)timeArray{

    //注意：数组时间是倒序的
    for (int i = (int)(timeArray.count -1); i > -1; i --) {
        TimeLabel *timeLabel = [[TimeLabel alloc]init];
        timeLabel.text = timeArray[i];
        [self.view addSubview:timeLabel];
        //设置label的tag值 注意：i从5开始
        timeLabel.tag = 12017 + i;
        [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).offset(-10*hl);
            make.width.equalTo(self.view).dividedBy(6);
            make.right.equalTo(self.view.mas_right).offset(1- i *[UIScreen mainScreen].bounds.size.width/6);
        }];
    }
}

//添加按钮
- (void)addSomebutton{
    UIButton *refreshBtn = [[UIButton alloc]init];
    _actionOrStopBtn = [[UIButton alloc]init];
    _backBtn = [[UIButton alloc]init];
    _nextBtn = [[UIButton alloc]init];
//设置标题
    [refreshBtn setTitle:@"刷新" forState:UIControlStateNormal];
    [_backBtn setTitle:@"上一页" forState:UIControlStateNormal];
    [_nextBtn setTitle:@"下一页" forState:UIControlStateNormal];

    [self setButtonAndaddButtonWithButton:refreshBtn];
    [self setButtonAndaddButtonWithButton:_actionOrStopBtn];
    [self setButtonAndaddButtonWithButton:_backBtn];
    [self setButtonAndaddButtonWithButton:_nextBtn];
//添加约束
    [refreshBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20*wl);
        make.top.equalTo(self.view.mas_bottom).offset(- 100*hl);
        make.size.mas_equalTo(CGSizeMake(80*wl, 40*hl));
    }];
    [_actionOrStopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(refreshBtn.mas_right).offset(20*wl);
        make.top.equalTo(refreshBtn);
        make.size.mas_equalTo(CGSizeMake(40*wl, 40*hl));
    }];
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_actionOrStopBtn.mas_right).offset(20*wl);
        make.top.equalTo(refreshBtn);
        make.size.equalTo(refreshBtn);
    }];
    [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_backBtn.mas_right).offset(20*wl);
        make.size.top.equalTo(_backBtn);
    }];
    [_actionOrStopBtn setBackgroundColor:[UIColor clearColor]];
    [_actionOrStopBtn setBackgroundImage:[UIImage imageNamed:@"action"] forState:UIControlStateNormal];
    [_backBtn setBackgroundColor:[UIColor lightGrayColor]];
    _backBtn.userInteractionEnabled = NO;
    //添加点击方法
    [_actionOrStopBtn addTarget:self action:@selector(actionBtnDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_backBtn addTarget:self action:@selector(backBtnDidSelected:) forControlEvents:UIControlEventTouchUpInside];
    [_nextBtn addTarget:self action:@selector(nextBtnDidSelected:) forControlEvents:UIControlEventTouchUpInside];
    [refreshBtn addTarget:self action:@selector(refreshBtnDidSelected:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setButtonAndaddButtonWithButton:(UIButton *)button{
    [self.view addSubview:button];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 8;
    [button.titleLabel setFont:TEXT_FONT];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor blueColor];
}

#pragma mark -- 按钮点击方法
//开始暂停按钮
- (void)actionBtnDidClicked:(UIButton *)button{
    if (button.selected == NO) {
        button.selected = YES;
        [button setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        TimeLabel *timeLabel = [self.view viewWithTag:(_imageArray.count - 1 + 12017)];
        [timeLabel.lineView setBackgroundColor:RGBACOLOR(38, 88, 202, 0.5)];
        //如果当前是最后一个变成第一个
        for (int i = 0; i < _imageArray.count; i++) {
            if ([_imageView.image isEqual:_imageArray[i]]) {
                if (i == 0) {
                    _imageView.image = [_imageArray objectAtIndex:_imageArray.count -1];
                    for (int i = (int)(_imageArray.count -2); i > -1; i --) {
                        //将后面四个全部变灰色
                        TimeLabel  *timeLabel = [self.view viewWithTag:(12017 + i)];
                        [timeLabel.lineView setBackgroundColor:RGBACOLOR(187, 200, 204, 0.5)];
                    }
                }
            }
        }
        //添加定时器
        _timer= [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
    }else if (button.selected == YES){
        //停止播放
        [self suspendedPlayWithBtn:button];
    }
}

//上一页按钮点击
- (void)backBtnDidSelected:(UIButton *)button{
    _nextBtn.backgroundColor = [UIColor blueColor];
    _nextBtn.userInteractionEnabled = YES;
    int num = [self getNumberOnImageView];
    ///如果是第二张，变为NO.1 且不可点击
    if (num == _imageArray.count - 2) {
        button.backgroundColor = [UIColor lightGrayColor];
        button.userInteractionEnabled = NO;
    }
    [_imageView setImage:(UIImage *)_imageArray[num +1]];
    TimeLabel *timeLabel = [self.view viewWithTag:12017 + num];
    ///变为灰色
    [timeLabel.lineView setBackgroundColor:RGBACOLOR(187, 200, 204, 0.5)];
    TimeLabel *timeLabel2 = [self.view viewWithTag:12017 + num +1];
    [timeLabel2.lineView setBackgroundColor:RGBACOLOR(38, 88, 202, 0.5)];
}

//下一页按钮点击
- (void)nextBtnDidSelected:(UIButton *)button{
    _backBtn.backgroundColor = [UIColor blueColor];
    _backBtn.userInteractionEnabled = YES;
    int num = [self getNumberOnImageView];
    if (num == 1) {
        button.backgroundColor = [UIColor lightGrayColor];
        button.userInteractionEnabled = NO;
    }
    //变为下一页，下一页对应lable设定为蓝色
    [_imageView setImage:(UIImage *)_imageArray[num -1]];
    TimeLabel *timelabel = [self.view viewWithTag:12017 + num - 1];
    //变蓝色
    [timelabel.lineView setBackgroundColor:RGBACOLOR(38, 88, 202, 0.5)];
    TimeLabel *timeLabel1 = [self.view viewWithTag:12017 + _imageArray.count -1];
    [timeLabel1.lineView setBackgroundColor:RGBACOLOR(38, 88, 202, 0.5)];
}

//刷新按钮点击
- (void)refreshBtnDidSelected:(UIButton *)button{
    //清空数组
    [_imageArray removeAllObjects];
    [_timeArray removeAllObjects];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[DataHandel sharedDataHandel]getLeiDaSumDataWithBlock:^(id object) {
        NSArray * leidaArray = (NSArray *)object;
        for (NSDictionary *dict in leidaArray) {
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dict objectForKey:@"path"]]]];
            ///将图片和时间分别加进数组
            [_timeArray addObject:[self getTimeStringWithString:[dict objectForKey:@"time"]]];
            if (image != nil) {
                [_imageArray addObject:image];
            }else{
                //请求失败
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = @"请求失败";
                hud.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5f];
                hud.offset = CGPointMake(0.f, 200);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
                });
            }
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        for (int i = 0;  i < _timeArray.count; i ++) {
            TimeLabel *timeLabel = [self.view viewWithTag:12017 + i];
            timeLabel.lineView.backgroundColor = RGBACOLOR(187, 200, 204, 0.5);
        }
        [_imageView setImage:[_imageArray objectAtIndex:_imageArray.count -1]];
    }];
}

- (int)getNumberOnImageView{
    for (int i = 0 ; i < _imageArray.count; i ++) {
        if ([_imageArray[i] isEqual:_imageView.image]) {
            return i;
        }
    }
    return 0;
}

#pragma mark -- 定时器方法，固定时间更换照片
-(void)changeImage{
    for (int i = 0; i < _imageArray.count; i ++) {
        if ([UIImageJPEGRepresentation(_imageView.image, 1) isEqual:UIImageJPEGRepresentation(_imageArray[i], 1)]) {
            _backBtn.userInteractionEnabled = YES;
            _backBtn.backgroundColor = [UIColor blueColor];
            if (i != 0 ) {
                //如果不是最后一个 (数组第一个是时间最晚的。)
                _imageView.image = (UIImage *)[_imageArray objectAtIndex:i - 1];
                TimeLabel *timeLabel = [self.view viewWithTag:(12017 + i - 1)];
                [timeLabel.lineView setBackgroundColor:RGBACOLOR(38, 88, 202, 0.5)];
                _nextBtn.userInteractionEnabled = YES;
                [_nextBtn setBackgroundColor:[UIColor blueColor]];
                return ;
            }else{
                //如果是最后一个
                //停止播放状态
                [self suspendedPlayWithBtn:_actionOrStopBtn];
                _nextBtn.backgroundColor = [UIColor lightGrayColor];
                _nextBtn.userInteractionEnabled = NO;
            }
        }
    }
}

#pragma mark -- 暂停播放
-(void)suspendedPlayWithBtn:(UIButton *)button{
    //关闭定时器
    [_timer setFireDate:[NSDate distantFuture]];
    [button setBackgroundImage:[UIImage imageNamed:@"action"] forState:UIControlStateNormal];
    button.selected = NO;
}
#pragma mark -- scrollView的代理方法,返回缩放的视图
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
     //_imageView.center = scrollView.center;
    return _imageView;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
